package com.jingbian.cppccbackend.service.impl.user;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingbian.cppccbackend.entity.Users;
import com.jingbian.cppccbackend.entity.WechatConstant;
import com.jingbian.cppccbackend.entity.dto.ChangePasswordDTO;

import com.jingbian.cppccbackend.entity.dto.UserDTO;
import com.jingbian.cppccbackend.mapper.user.UsersMapper;
import com.jingbian.cppccbackend.service.user.UsersService;
import com.jingbian.cppccbackend.utils.HttpClientUtil;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-02-09
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private WechatConstant wechatConstant;

    @Override
    public Users getUserInfo(String phone) {
        return usersMapper.getUserInfo(phone);
    }

//    @Override
//    public boolean add(UserDTO userDTO) {
//        Users user = new Users();
//        BeanUtils.copyProperties(userDTO, user);
//        user.setStatus("未处理");
//        user.setRegistrationTime(LocalDateTime.now());
//        user.setUpdateTime(LocalDateTime.now());
//        // 获取微信唯一标识openid
//        String openid = getOpenid(userDTO.getCode());
//        if(openid == null){
//            return false;
//        }
//        user.setOpenid(openid); // 设置微信用户唯一标识
//        Users queryUser = usersMapper.getUserInfo(user.getPhone());
//        if (queryUser != null) {
//            return false;
//        }
//        System.out.println(user);
//        usersMapper.insert(user);
//        return true;
//    }
@Override
public boolean add(UserDTO userDTO) {
    // 查询是否存在该手机号的记录
    Users existingUser = usersMapper.getUserInfo(userDTO.getPhone());

    // 获取openid
    String openid = getOpenid(userDTO.getCode());
    if(openid == null){
        return false;
    }

    if (existingUser != null) {
        // 如果存在记录，检查状态
        if (existingUser.getStatus().equals("已驳回")) {
            // 如果是驳回状态，创建新记录
            Users newUser = new Users();
            BeanUtils.copyProperties(userDTO, newUser);
            newUser.setStatus("未处理");
            newUser.setRegistrationTime(LocalDateTime.now());
            newUser.setUpdateTime(LocalDateTime.now());
            newUser.setOpenid(openid);
            newUser.setRegistrationCount(existingUser.getRegistrationCount() + 1);
            newUser.setIsActive(true);

            // 将原记录标记为非活动
            existingUser.setIsActive(false);
            usersMapper.updateById(existingUser);

            // 插入新记录
            usersMapper.insert(newUser);
            return true;
        } else {
            // 如果不是驳回状态，不允许重复注册
            return false;
        }
    } else {
        // 首次注册
        Users user = new Users();
        BeanUtils.copyProperties(userDTO, user);
        user.setStatus("未处理");
        user.setRegistrationTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setOpenid(openid);
        user.setRegistrationCount(1);
        user.setIsActive(true);

        usersMapper.insert(user);
        return true;
    }
}

    @Override
    public Users wxLogin(String code) {
        String openid = getOpenid(code);
        if(openid == null){
            return null;
        }
        Users users = usersMapper.getByOpenid(openid);
        return users;
    }

    // 更新用户密码
    @Override
    public int updateUsers(ChangePasswordDTO changePasswordDTO) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        changePasswordDTO.setPhone(claims.get("phone").toString());
        LambdaUpdateWrapper<Users> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Users::getPhone, changePasswordDTO.getPhone()).eq(Users::getPassword,changePasswordDTO.getOldPassword())
                .eq(Users::getIsActive,true).set(Users::getPassword, changePasswordDTO.getNewPassword());
        return usersMapper.update(updateWrapper);
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",wechatConstant.getAppid());
        map.put("secret",wechatConstant.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
